package com.storebits.validators;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class DateRangeValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object value)
            throws ValidatorException {
        
        // Cast the value of the entered date to Date.        
        Date firstDate = (Date) value;
        UIInput confirmComponent = (UIInput) component.getAttributes().get("confirm");
        String secondDateAsStr = (String) confirmComponent.getSubmittedValue();
        if (firstDate == null || secondDateAsStr == null) {
            return; // Let required="true" do its job.
        }
        
        String pattern = "dd/MM/yyyy";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date secondDate = null;
        try {
            secondDate = format.parse(secondDateAsStr);
            System.out.println(secondDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // Check if they both are filled in.

        
        Calendar today = Calendar.getInstance();
        today.add(Calendar.DAY_OF_MONTH, -1);
        
        if (firstDate.before(today.getTime())) {
            confirmComponent.setValid(false); // So that it's marked invalid.
             FacesMessage validationMessage = new FacesMessage("Please enter a valid"
                    + " start date");
            validationMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(validationMessage);
        }

        if (firstDate.after(secondDate)) {
            confirmComponent.setValid(false); // So that it's marked invalid.
            FacesMessage validationMessage = new FacesMessage("Please enter a valid"
                    + " date range");
            validationMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(validationMessage);
        }
    }
}
